$(function(){             
    var staffTable = null; 
    var selIptID = ""; //记录当前文本框的工号
    var opts = {
        targetId: "personTable",
        templateId: "tableperson",
        settings: {
            url:DI.queryRegionHandler,
            ajaxType:"json",
            sourceInterface:{INum:"totalSize",IData:"records"},
            paginationIndexName:{
                "peerpageRows":"pageSize",
                "currentPage":"pageNo"
            }
        },
        customFuncs: {
            editnumber: function(){
                var _self = $(this),
                    _staff = _self.find(".staff-code");
                selIptID = _staff.text();
                $(this).find(".staff-code").hide();
                $(this).find("input").show().focus().val(selIptID);
                $(this).find("input").unbind("blur");
                $(this).find("input").bind("blur",function(){
                    $(this).hide();
                    _staff.show().html(selIptID);
                    _self.find(".err-box").remove();
                });
            },
            checknumber: function(row){
                var iptVal = $(this).val(),
                    reg = /^\d{8}$/,
                    _self = $(this),
                    parentTd = _self.parents("td");
                this.value = iptVal.replace(/\D/g,'');
                //必须输入8位数字
                if(!reg.test(iptVal)){
                    if(_self.next(".err-box").length == 0){                       
                        _self.after('<div class="err-box"><p class="u-error">请输入8位数字工号</p></div>')    
                    }else{
                        _self.next(".err-box").find(".u-error").text("请输入8位数字工号");
                    }                    
                }else{
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        data:{"staffCode":iptVal},
                        url: DI.queryNamebyId,
                        success: function(data){
                            if(data.retFlag == 1){
                                _self.next(".err-box").remove();
                                parentTd.next(".staff-name").html(data.data.staffName);
                                //_self.bind("blur",opts.customFuncs.savenumber(iptVal));
                                _self.unbind("blur");
                                _self.bind("blur",function(){
                                    //必须输入8位数字
                                    if(!reg.test(iptVal)){                    
                                        if(_self.next(".err-box").length == 0){                       
                                            _self.after('<div class="err-box"><p class="u-error">请输入8位数字工号</p></div>')    
                                        }else{
                                            _self.next(".err-box").find(".u-error").text("请输入8位数字工号");
                                        }
                                    }else{
                                        var staffName = parentTd.next(".staff-name").html();
                                        var regionHandlerId = _self.prev("input").val(); 
                                        $.ajax({
                                            type: "post",
                                            dataType: "json",
                                            data:{"regionHandlerId":row.Id,"staffCode":iptVal,"staffName":staffName},
                                            url: DI.updateRegionHandler,
                                            success: function(data){
                                                if(data.retFlag == 1){
                                                    _self.hide();
                                                    parentTd.find(".staff-code").show().html(iptVal);
                                                    parentTd.find(".err-box").remove();
                                                }else{
                                                    _self.hide();
                                                    parentTd.find(".staff-code").show().html(selIptID);
                                                    parentTd.find(".err-box").remove();
                                                    parentTd.next(".staff-name").html("");
                                                    PLATFORM.showTips("error", data.errorMessage);
                                                }
                                            },
                                            error: function(err){
                                                console.log(err);
                                            }
                                        });
                                    }
                                });
                                
                            }else{
                                if(_self.next(".err-box").length == 0){                       
                                    _self.after('<div class="err-box"><p class="u-error">'+data.errorMessage+'</p></div>')    
                                }else{
                                    _self.next(".err-box").find(".u-error").text(data.errorMessage);
                                }
                                _self.unbind("blur");
                                _self.bind("blur",function(){
                                    _self.hide();
                                    parentTd.find(".staff-code").show().html(selIptID);
                                    parentTd.find(".err-box").remove();
                                });
                            }
                        },
                        error: function(err){
                            console.log(err);
                        }
                    });
                }
            }
        }
        
    };
    staffTable = SwiftUI.swiftTable.getInstance(opts);
    
    $.ajax({
        type: "post",
        dataType: "json",
        url: DI.queryAllRegion,
        success: function(data){
            if(data.retFlag == 1){
                mainCtrl.allRegions = data.regions;
                mainCtrl.regionList = data.regions;
            }else{
                console.log("获取所有大区失败，请检查原因");
            }
        },
        error: function(err){
            console.log(err);
        }
    });
    
//  var thiswinurl = window.location.href,
//      searchKey = "authKey",
//      authKeyIdx = thiswinurl.indexOf(searchKey),
//      authKeyStr = (authKeyIdx==-1)?"":thiswinurl.substring(authKeyIdx+(searchKey.length+1)),
//      authkeyparam = (authKeyStr=="")?"":("?authKey="+authKeyStr);
    
    var mainCtrl = avalon.define({
        $id: "mainController",                  
        regioncode: "",
        regionname: "",
        regiontext: "",
        allRegions: [],
        regionList: [],
        search: function(){
            if(mainCtrl.regiontext == ""){
                mainCtrl.regioncode = "";
                mainCtrl.regionname = "";
            }
            var searchParam = {"regionCode":mainCtrl.regioncode,"regionName":mainCtrl.regionname};
            staffTable.search(searchParam);
        },
        showRegion: function(){
            $(".clone-select ul").show();
        },
        searchRegion: function(){
//          setTimeout(function(){
//              
//          },1000);
            var searchList = [];
            for(var i = 0; i < mainCtrl.allRegions.length; i++){
                var regionName = mainCtrl.allRegions[i].regionName,
                    regionCode = mainCtrl.allRegions[i].regionCode;
                if(regionName.indexOf(mainCtrl.regiontext) != -1 || regionCode.indexOf(mainCtrl.regiontext) != -1) {
                    searchList.push(mainCtrl.allRegions[i]);
                }
            }
            mainCtrl.regionList = searchList;
        },
        selectRegion: function(){
            $(this).addClass("sel").siblings("li").removeClass("sel");
            $(".clone-select ul").hide();
            var regiontxt = $(this).text();
            var name = regiontxt.substring(regiontxt.indexOf("-")+2,regiontxt.length);
            var code = regiontxt.substring(0,regiontxt.indexOf("-")-1);
            mainCtrl.regiontext = name;
            mainCtrl.regionname = name;
            mainCtrl.regioncode = code;
        }
    });
    document.onclick = function (event){     
        var e = event || window.event;  
        var elem = e.srcElement||e.target;
        var selLen = $(elem).parents(".clone-select").length;
        //如果他们的父节点没有.clone-select  则说明点击的不是下拉框这个区域，隐藏
        if(selLen == 0){
            $(".clone-select ul").hide();
            var regionTxt = mainCtrl.regiontext; 
            if(regionTxt != ""){
                var isExist = false;
                for(var i = 0; i < mainCtrl.allRegions.length; i++){
                    var regionName = mainCtrl.allRegions[i].regionName,
                        regionCode = mainCtrl.allRegions[i].regionCode;
                    if(regionName == regionTxt || regionCode == regionTxt) {
                        mainCtrl.regiontext = regionName;
                        isExist = true;
                        break;
                    }
                }
                if(!isExist){
                    mainCtrl.regiontext = "";
                    mainCtrl.regionList = mainCtrl.allRegions;
                }
            }
        }
    }
    
    avalon.scan();
});